//
//  FWQQWBClient.m
//  FWShare
//
//  Created by 范文青 on 14-6-15.
//  Copyright (c) 2014年 fwq. All rights reserved.
//

#import "FWQQWBClient.h"
#import "NSMutableURLRequest+FWHTTPAddition.h"
#import "FWQQWBStatusWithPicParam.h"
#import "FWAuthUser.h"
#import "FWShareValues.h"
#import "FWShare.h"
#import "FWAccountProcotol.h"
#import "BBlock.h"
@implementation FWQQWBClient
- (void)share:(NSString *)content
{
    [self share:content pic:nil];
}
- (void)share:(NSString *)content pic:(NSData *)pic
{
    
    FWMultiPartFileData  *fileData = nil;
    if (pic != nil) {
        fileData = [FWMultiPartFileData new];
        [fileData setMimeType:@"image/jepg"];
        [fileData setData:pic];
        [fileData setFileName:@"image"];
    }

    
    FWAuthUser  *user = [FWAuthUser userByMediaType:QQ_WEIBO];
    FWQQWBStatusWithPicParam *status = [FWQQWBStatusWithPicParam new];
    [status setAccess_token:user.token.access_token];
    [status setOauth_consumer_key:[[[FWShare shareCenter] accounts] QQWeiBoAppKey]];
    [status setOpenid:user.token.uid];
    [status setContent:content];
    [status setPic:fileData];
    
    NSMutableURLRequest *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://open.t.qq.com/api/t/add_pic"] parameters:[status dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodPOST contentType:FWPostContentTypeMultiPart];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSDictionary  *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([self isValid:dic]) {
                if (self.shareComplete) {
                    self.shareComplete(YES,nil);
                }
            }else{
                if (self.shareComplete) {
                    NSError  *error = [NSError errorWithDomain:@"FWQQWBShareFailed" code:[[dic objectForKey:@"errcode"] intValue] userInfo:@{@"message": [dic objectForKey:@"msg"]}];
                    self.shareComplete(NO,error);
                }
            }
        }];
   }];
}

- (BOOL)isValid:(NSDictionary *)dic{
    if ([[dic objectForKey:@"ret"] intValue] == 0) {
        return YES;
    }
    return NO;
}
@end
